# app.py
from flask import Flask, render_template, request, jsonify
from alibabacloud_facebody20191230.client import Client as facebodyClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util import models as util_models
import os
import oss2
import uuid
from werkzeug.utils import secure_filename
from auth import auth_login, require_login
from alibabacloud_facebody20191230.models import CompareFaceAdvanceRequest
from urllib.request import urlopen
import io

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = './'
app.config['MAX_CONTENT_LENGTH'] = 5 * 1024 * 1024  # 5MB限制

@app.route('/login', methods=['POST', 'GET'])
def login():
    return auth_login()

# 初始化OSS客户端
endpoint = os.environ['OSS_ENDPOINT']
auth = oss2.Auth(os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'], os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'])
bucket = oss2.Bucket(auth, endpoint, os.environ['OSS_BUCKET'])


def create_client() -> facebodyClient:
    """创建人脸比对客户端"""
    config = open_api_models.Config(
        access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
        access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
    )
    config.endpoint = 'facebody.cn-shanghai.aliyuncs.com'
    return facebodyClient(config)


@app.route('/')
@require_login
def index():
    return render_template('index.html')


@app.route('/api/upload_face', methods=['POST'])
def upload_face():
    if 'file' not in request.files:
        return jsonify({"error": "No file part"}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({"error": "No selected file"}), 400

    # 生成唯一文件名
    ext = secure_filename(file.filename).split('.')[-1]
    object_name = f"faces/{uuid.uuid4().hex}.{ext}"

    try:
        # 直接上传到OSS
        result = bucket.put_object(object_name, file)
        if result.status != 200:
            return jsonify({"error": "OSS upload failed"}), 500
        url = bucket.sign_url('GET', object_name, 3600 * 24)
        return jsonify({"url": url})
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@app.route('/api/compare_faces', methods=['POST'])
def compare_faces():
    data = request.get_json()
    if not data or 'image1' not in data or 'image2' not in data:
        return jsonify({"error": "Missing image URLs"}), 400

    client = create_client()
    url1 = data['image1']
    url2 = data['image2']
    

    img1 = io.BytesIO(urlopen(url1).read())
    img2 = io.BytesIO(urlopen(url2).read())
    

    request_body = CompareFaceAdvanceRequest()
    request_body.image_urlaobject = img1
    request_body.image_urlbobject = img2


    try:
        response = client.compare_face_advance(
            request_body,
            util_models.RuntimeOptions()
        )
        return jsonify({
            "confidence": response.body.data.confidence,
        })
    except Exception as error:
        error_info = {
            "error": error.message,
            "recommend": getattr(error, 'data', {}).get("Recommend", "")
        }
        print(error_info)
        return jsonify(error_info), 500


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
